package com.serkol.ams.controller.api;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.hutool.core.codec.Base62;
import cn.hutool.core.img.ImgUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.serkol.ams.bean.MyPageOld;
import com.serkol.ams.bean.Result;
import com.serkol.ams.entity.LoginLog;
import com.serkol.ams.entity.Pictures;
import com.serkol.ams.service.PicturesService;
import com.serkol.ams.service.UsersService;
import com.serkol.annotation.IsLogin;
import com.serkol.constant.AuthConstant;
import com.serkol.constant.ResultConstant;
import com.serkol.exception.SerKolException;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import jakarta.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Random;

@RestController
@RequestMapping("api/upload")
public class UploadApiController {

    @Autowired
    private PicturesService picturesService;

    @Value("${upload.path}")
    private String uploadpath;
    @Value("${upload.host}")
    private String uploadhost;
    @Autowired
    private UsersService userService;
    @Autowired
    private WxMaService wxMaService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/image")
    public Result image(HttpServletRequest request, @RequestParam("file") MultipartFile file, @RequestParam(name = "appcation_name", defaultValue = "public") String appcationName, @RequestParam(name = "type", defaultValue = "0") int type) throws SerKolException {
        Result result = new Result();
        AuthConstant.setPathUrl("");
        long request_id = System.currentTimeMillis();
        System.out.println("File:" + file.isEmpty());
        if (file.isEmpty()) {
            throw new NullPointerException("  Helllo ");
        }

        try {


            String contentType = file.getContentType();
            String[] split = contentType.split("/");
            String type1 = split[1];
            BufferedImage bi = ImageIO.read(file.getInputStream());
            String filem = "upload/image/" + appcationName + "/";

            Pictures pictures = new Pictures();
            Random random = new Random();
            int i1 = random.nextInt(1000000000);
            String fileName = filem + System.currentTimeMillis() + "serkol" + i1 + "." + type1;
            String path = uploadhost + fileName;
            String pathname = uploadpath + fileName;
            filem = uploadpath + filem;
            pictures.setName(file.getOriginalFilename());
            pictures.setIstype(type);
            pictures.setH(bi.getHeight());
            pictures.setW(bi.getWidth());
            //   pictures.setIstype(0);
            pictures.setAppcationName(appcationName);
            pictures.setType(type1);
            pictures.setUrl(fileName);
            pictures.setRequestId(request_id);
            System.out.println(pictures.toString());
            System.out.println(filem);
            System.out.println(path);
            System.out.println(pathname);
            boolean edit = picturesService.save(pictures);


            if (edit) {
                File file1 = new File(filem);
                if (!file1.exists()) {
                    file1.mkdirs();
                }
                File dest = new File(pathname);

                file.transferTo(dest);
                //  result.setData(edit);
                QueryWrapper<Pictures> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda()
                        .eq(Pictures::getRequestId, request_id);
                //REQUEST_ID
                AuthConstant.setPathUrl(uploadhost);

                Pictures one = picturesService.getOne(queryWrapper);
                result.setData(one);
                result.setStatus(ResultConstant.SUCSESS);
            } else {
                //result.setMsg(" hhh ");
                result.setStatus(ResultConstant.FAIL);
            }


        } catch (IOException e) {
            e.printStackTrace();
            throw new SerKolException(ResultConstant.FAIL);

        }


        return result;

    }


    @IsLogin
    @PostMapping("/avatar")
    public Result avatar(HttpServletRequest request, @RequestParam("file") MultipartFile file, @RequestParam(name = "appcation_name", defaultValue = "avatar") String appcationName, @RequestParam(name = "type", defaultValue = "7") int type) throws SerKolException {
        Result result = new Result();
        LoginLog loginLog = AuthConstant.getLoginLog();
        AuthConstant.setPathUrl("");
        long request_id = System.currentTimeMillis();
        System.out.println("File:" + file.isEmpty());
        if (file.isEmpty()) {
            throw new NullPointerException("  Helllo ");
        }

        try {


            String contentType = file.getContentType();
            String[] split = contentType.split("/");
            String type1 = split[1];
            BufferedImage bi = ImageIO.read(file.getInputStream());
            String filem = "u" +
                    "+" +
                    "pload/image/" + appcationName + "/";

            Pictures pictures = new Pictures();
            Random random = new Random();
            int i1 = random.nextInt(1000000000);
            String fileName = filem + System.currentTimeMillis() + "serkol" + i1 + "." + type1;
            String path = uploadhost + fileName;
            String pathname = uploadpath + fileName;
            filem = uploadpath + filem;

            pictures.setIstype(type);
            pictures.setH(bi.getHeight());
            pictures.setW(bi.getWidth());
            //   pictures.setIstype(0);
            pictures.setAppcationName(appcationName);
            pictures.setType(type1);
            pictures.setUrl(fileName);
            pictures.setRequestId(request_id);
            System.out.println(pictures.toString());
            System.out.println(filem);
            System.out.println(path);
            System.out.println(pathname);
            boolean edit = picturesService.save(pictures);


            if (edit) {
                File file1 = new File(filem);
                if (!file1.exists()) {
                    file1.mkdirs();
                }
                File dest = new File(pathname);

                file.transferTo(dest);
                //  result.setData(edit);
                QueryWrapper<Pictures> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda()
                        .eq(Pictures::getRequestId, request_id);
                //REQUEST_ID
                AuthConstant.setPathUrl(uploadhost);
                Pictures one = picturesService.getOne(queryWrapper);
                if(one != null) {
                    boolean b=userService.changeAvatar(loginLog.getUserId(),one.getId(),one.getUrl());
                }
                result.setData(one);
                result.setStatus(ResultConstant.SUCSESS);
            } else {
                //result.setMsg(" hhh ");
                result.setStatus(ResultConstant.FAIL);
            }


        } catch (IOException e) {
            e.printStackTrace();
            throw new SerKolException(ResultConstant.FAIL);

        }


        return result;

    }



    @IsLogin
    @GetMapping("/inviteCode")
    public Result inviteCode(HttpServletRequest request, @RequestParam(name = "appcation_name", defaultValue = "wechat/qrcode") String appcationName) throws SerKolException, WxErrorException {
        Result result = new Result();
        AuthConstant.setPathUrl("");
        File file = wxMaService.getQrcodeService().createWxaCode("pages/index/user", "");
        long request_id = System.currentTimeMillis();
        //   System.out.println("File:" + file.isEmpty());
        try {
            String contentType = "image/png";
            String[] split = contentType.split("/");
            String type = split[1];
            BufferedImage bi = ImageIO.read(file);
            String filem = "upload/image/" + appcationName + "/";

            Pictures pictures = new Pictures();
            Random random = new Random();
            int i1 = random.nextInt(1000000000);
            String fileName = filem + System.currentTimeMillis() + "serkol" + i1 + "." + type;
            String path = uploadhost + fileName;
            String pathname = uploadpath + fileName;
            filem = uploadpath + filem;


            pictures.setH(bi.getHeight());
            pictures.setW(bi.getWidth());
            pictures.setIstype(5);
            pictures.setAppcationName(appcationName);
            pictures.setType(type);
            pictures.setUrl(fileName);
            pictures.setRequestId(request_id);
            System.out.println(pictures.toString());
            System.out.println(filem);
            System.out.println(path);
            System.out.println(pathname);
            boolean edit = picturesService.save(pictures);


            if (edit) {
                File file1 = new File(filem);
                if (!file1.exists()) {
                    file1.mkdirs();
                }
                File dest = new File(pathname);
                ImgUtil.flip(file, dest);
                //  file.transferTo(dest);
                //  result.setData(edit);
                QueryWrapper<Pictures> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda()
                        .eq(Pictures::getRequestId, request_id);
                //REQUEST_ID

                Pictures one = picturesService.getOne(queryWrapper);
                result.setData(one);
                result.setStatus(ResultConstant.SUCSESS);
            } else {
                //result.setMsg(" hhh ");
                result.setStatus(ResultConstant.FAIL);
            }


        } catch (IOException e) {
            e.printStackTrace();
            throw new SerKolException(ResultConstant.FAIL);

        }


        return result;

    }


    // @GetMapping("/agentInviteCode")
    @IsLogin
    @GetMapping(value = "agentInviteCode")
    public Result agentInviteCode(HttpServletRequest request, @RequestParam(name = "page", defaultValue = "pages/index/index") String page,
                                  @RequestParam(name = "type", defaultValue = "0") Integer type) throws SerKolException, WxErrorException, IOException {
        Result result = new Result();
        AuthConstant.setPathUrl("");
        LoginLog loginLog = AuthConstant.getLoginLog();
        String pages = page + "?type=" + type + "&userId=" + loginLog.getUserId();
        String key = Base62.encode(pages);
        File file = picturesService.invalidQrCode(key, pages);

   /*   LoginLog loginLog = AuthConstant.getLoginLog();
        String pages=page+"?type="+type+"&userId="+loginLog.getUserId();
      String   key = Base62.encode(pages);
        if(redisTemplate.hasKey(key)){
            String o = (String) redisTemplate.opsForValue().get(key);
            byte[] bytes = Base64.decodeBase64(o);

            return Result.ok(bytes);
        }else {
            File file = wxMaService.getQrcodeService().createWxaCode(pages);
            byte[] bytes = Files.readAllBytes(file.toPath());
            System.out.println(bytes.toString());
            redisTemplate.opsForValue().set(key, bytes);
            return Result.ok(bytes);
        }*/
        byte[] bytes = Files.readAllBytes(file.toPath());
        return Result.ok(bytes);
    }

    @PostMapping("/video")
    public Result video( @RequestParam("file") MultipartFile file, @RequestParam(name = "appcation_name", defaultValue = "public") String appcationName, @RequestParam(name = "type", defaultValue = "0") int type) throws SerKolException {
        Result result = new Result();
        AuthConstant.setPathUrl("");
        long request_id = System.currentTimeMillis();
        System.out.println("File:" + file.isEmpty());
        System.out.println("File:" + file.getSize());
        if (file.isEmpty()) {
            throw new NullPointerException("  Helllo ");
        }

        try {


            String contentType = file.getContentType();
            String[] split = contentType.split("/");
            String type1 = split[1];
            BufferedImage bi = ImageIO.read(file.getInputStream());
            String filem = "upload/video/" + appcationName + "/";

            Pictures pictures = new Pictures();
            Random random = new Random();
            int i1 = random.nextInt(1000000000);
            String fileName = filem + System.currentTimeMillis() + "serkol" + i1 + "." + type1;
            String path = uploadhost + fileName;
            String pathname = uploadpath + fileName;
            filem = uploadpath + filem;

            pictures.setIstype(type);
            pictures.setName(file.getOriginalFilename());
            //   pictures.setIstype(0);
            pictures.setAppcationName(appcationName);
            pictures.setType(type1);
            pictures.setUrl(fileName);
            pictures.setRequestId(request_id);
            System.out.println(pictures.toString());
            System.out.println(filem);
            System.out.println(path);
            System.out.println(pathname);
            boolean edit = picturesService.save(pictures);


            if (edit) {
                File file1 = new File(filem);
                if (!file1.exists()) {
                    file1.mkdirs();
                }
                File dest = new File(pathname);

                file.transferTo(dest);
                //  result.setData(edit);
                QueryWrapper<Pictures> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda()
                        .eq(Pictures::getRequestId, request_id);
                //REQUEST_ID
                AuthConstant.setPathUrl(uploadhost);

                Pictures one = picturesService.getOne(queryWrapper);
                result.setData(one);
                result.setStatus(ResultConstant.SUCSESS);
            } else {
                //result.setMsg(" hhh ");
                result.setStatus(ResultConstant.FAIL);
            }


        } catch (IOException e) {
            e.printStackTrace();
            throw new SerKolException(ResultConstant.FAIL);

        }


        return result;

    }



    @GetMapping("/findByPageList")
    public Result findByPageList(@RequestParam(name = "pageSize", defaultValue = "24") int pageSize, @RequestParam(name = "page", defaultValue = "0") int page, @RequestParam(name = "type", defaultValue = "0") int type) {
        AuthConstant.setPathUrl(uploadhost);
        Result result = new Result();

      return picturesService.findByList(pageSize,page, type);

    }


}
